<template>
  <div class="comment-container">
    <h2 style="margin-bottom: 10px;font-weight: bold">商品评论</h2>
    <p v-if="!props.isBought">购买后才可以发评论哦😀</p>
    <!-- 评论输入框 -->
    <div class="comment-input" v-if="isBought">
      <el-input
          v-model="newComment"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
      />
      <el-button
          type="primary"
          @click="submitComment"
          :disabled="!newComment.trim()"
      >
        发表评论
      </el-button>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div
          v-for="comment in topLevelComments"
          :key="comment.id"
          class="comment-item"
      >
        <!-- 主评论内容 -->
        <div class="comment-content">
          <div class="comment-header">
            <el-avatar :size="32" :src="comment.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            <div class="user-info">
              <span class="username">{{ comment.userName }}</span>
              <span class="time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
          <div class="comment-text">
            {{ comment.content }}
            <span style="color: red;float: right;font-size: small" v-if="currentUser.id === comment.userId">删除</span>
          </div>
          <div class="comment-actions" v-if="props.isBought">
            <span class="reply-btn" @click="startReply(comment)">
              回复
            </span>
          </div>
        </div>
        <!-- 回复输入框（仅在点击回复时显示） -->
        <div
            v-if="replyingTo === comment.id"
            class="reply-input"
        >
          <el-input
              v-model="replyContent"
              type="textarea"
              :rows="2"
              :placeholder="`回复 @${comment.userName}`"
          />
          <div class="reply-buttons">
            <el-button
                size="small"
                @click="cancelReply"
            >
              取消
            </el-button>
            <el-button
                v-if="props.isBought"
                type="primary"
                size="small"
                @click="submitReply(comment)"
                :disabled="!replyContent.trim()"
            >
              回复
            </el-button>
          </div>
        </div>

        <!-- 回复列表   看该主评论是否有子代品论-->
        <div
            v-if="hasReplies(comment.id)"
            class="replies"
        >
          <div
              v-for="reply in getReplies(comment.id)"
              :key="reply.id"
              class="reply-item"
          >
            <div class="comment-header">
              <el-avatar :size="28" :src="reply.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
              <div class="user-info">
                <span class="username">{{ reply.userName }}</span>
                <span class="time">{{ formatTime(reply.createTime) }}</span>
              </div>
            </div>
            <div class="comment-text">
              <template v-if="reply.parentUserName">
                回复 <span class="reply-to">@{{ reply.parentUserName }}</span>：
              </template>
              {{ reply.content }}

            </div>
            <div class="comment-actions" v-if="props.isBought">
              <span class="reply-btn" @click="startReply(reply)">
                回复
              </span>
            </div>

            <!-- 对回复的回复输入框 -->
            <div
                v-if="replyingTo === reply.id"
                class="reply-input"
            >
              <el-input
                  v-model="replyContent"
                  type="textarea"
                  :rows="2"
                  :placeholder="`回复 @${reply.userName}`"
              />
              <div class="reply-buttons">
                <el-button
                    size="small"
                    @click="cancelReply"
                >
                  取消
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="submitReply(reply)"
                    :disabled="!replyContent.trim()"
                >
                  回复111
                </el-button>
              </div>
            </div>
          </div>

          <!-- 查看更多回复 -->
          <div
              v-if="getReplies(comment.id).length > 2 && !showAllReplies[comment.id]"
              class="view-more"
              @click="toggleShowAll(comment.id)"
          >
            展开更多{{ replyCounts[comment.id] }}条回复
            <el-icon><ArrowDown /></el-icon>
          </div>
          <div
              v-else-if="getReplies(comment.id).length > 3 && showAllReplies[comment.id]"
              class="view-more"
              @click="toggleShowAll(comment.id)"
          >
            收起回复
            <el-icon><ArrowUp /></el-icon>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <div class="pagination" v-if="totalComments > pageSize">
        <el-pagination
            small
            layout="prev, pager, next"
            :total="totalComments"
            :page-size="pageSize"
            @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>
<script  setup lang="ts">
import {ref, computed, onMounted} from 'vue'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import {useRoute} from "vue-router";
import {GET_ID,GET_AVATAR,GET_USER_NAME} from "@/utils/token"
import request from "@/utils/request";
import {ElMessage} from "element-plus";
    //获取当前路由上面的
const route = useRoute();

const props = defineProps({
  isBought: {
    type: Boolean,
    default: false, // 默认未购买
  },
});
// 获取路由参数中的 id
const commodityId = route.params.id as string; // 获取路由参数中的 id
console.log("commodityId ",commodityId)
//当前用户的信息
const currentUser = {
  id: GET_ID(),
  userName: GET_USER_NAME(),
  avatar: GET_AVATAR(),
}

console.log("currentUser ",currentUser)

const comments =ref([])

    const newComment = ref('')
    const replyContent = ref('')
    const replyingTo = ref(null)
    const showAllReplies = ref({})
    const currentPage = ref(1)
    const pageSize = ref(300)

    // 获取顶级评论
    const topLevelComments = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return comments.value
          .filter(comment => !comment.parentId)
          .slice(start, end)
    })

    // 获取某个评论的回复
    const getReplies = (commentId) => {
      const allReplies = comments.value
          .filter(comment => comment.parentId === commentId)
          .sort((a, b) => new Date(a.createTime) - new Date(b.createTime))

      // 如果没展开全部，只显示前3条
      if (!showAllReplies.value[commentId] && allReplies.length > 3) {
        return allReplies.slice(0, 3)
      }
      return allReplies
    }

    // 检查是否有回复
    const hasReplies = (commentId) => {
      return comments.value.some(comment => comment.parentId === commentId)
    }

    // 计算回复数量
    const replyCounts = computed(() => {
      const counts = {}
      comments.value.forEach(comment => {
        if (comment.parentId) {
          counts[comment.parentId] = (counts[comment.parentId] || 0) + 1
        }
      })
      return counts
    })

    // 格式化时间
    const formatTime = (time) => {
      const now = new Date()
      const commentTime = new Date(time)
      const diff = now - commentTime

      // 小于1分钟
      if (diff < 60000) return '刚刚'
      // 小于1小时
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
      // 今天
      if (commentTime.toDateString() === now.toDateString()) {
        return commentTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      }
      // 昨天
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      if (commentTime.toDateString() === yesterday.toDateString()) {
        return `昨天 ${commentTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`
      }
      // 更早
      return commentTime.toLocaleDateString([], { month: 'short', day: 'numeric' })
    }

    //用户提交父级评论
    const commentItem=ref({
      postId: undefined,
      userId: undefined,
      userName: "",
      avatar: "",
      content: "",
      parentId: undefined,
      parentUserName: "",
      createTime:"",
      updateTime:"",
    })


    // 提交新评论
    const submitComment =async () => {
      if (!newComment.value.trim()) return
      commentItem.value={
        //@ts-ignore
        postId: commodityId,

        content: newComment.value.trim(),
        //@ts-ignore
        parentId: null,
        //@ts-ignore
        parentUserName:null,

      }
      console.log("顶级评论 is ", commentItem.value)

      //发请求

      const res=await request.post("/api/review/add", commentItem.value)
      console.log("提交评论 res is ",res)
      if(res.code===200){
        ElMessage.success("评论成功")
      }
      const newId=res.data.id
      comments.value.unshift({
        id: newId,
        postId: commodityId,
        userId: currentUser.id,
        userName: currentUser.userName,
        avatar: currentUser.avatar,
        content: newComment.value.trim(),
        parentId: null,
        parentUserName: null,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
      })
      console.log("conmemnts array is ",comments.value)

      newComment.value = ''
    }

    // 开始回复
    const startReply = (comment) => {
      replyingTo.value = comment.id
      replyContent.value = ''
    }
    // 取消回复
    const cancelReply = () => {
      replyingTo.value = null
      replyContent.value = ''
    }

    // 提交回复
    const submitReply = async (parentComment) => {
      if (!replyContent.value.trim()) return

      const isReplyToReply = parentComment.parentId !== null
      commentItem.value={
        //@ts-ignore
        postId: commodityId,
        content: replyContent.value.trim(),
        parentId: isReplyToReply ? parentComment.parentId : parentComment.id,
        parentUserName:parentComment.userName,
      }
      console.log("子代评论 is ", commentItem.value)
      const res=await request.post("/api/review/add", commentItem.value)
      console.log("提交子代评论 res is ",res)
      if(res.code===200){
        ElMessage.success("评论成功")
        const newId=res.data.id
        comments.value.push({
          id: newId,
          postId: parentComment.postId,
          userId: currentUser.id,
          userName: currentUser.userName,
          avatar: currentUser.avatar,
          content: replyContent.value.trim(),
          parentId: isReplyToReply ? parentComment.parentId : parentComment.id,
          parentUserName: parentComment.userName,
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString(),
        })
      }

      console.log("提交回复 comments is ",comments.value)
      replyContent.value = ''
      replyingTo.value = null
    }

    // 切换显示全部回复
    const toggleShowAll = (commentId) => {
      showAllReplies.value = {
        ...showAllReplies.value,
        [commentId]: !showAllReplies.value[commentId]
      }
    }

    // 分页变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    // 总评论数
    const totalComments = computed(() => {
      console.log("顶级评论 num is",comments.value.filter(comment => !comment.parentId).length)
      return comments.value.filter(comment => !comment.parentId).length
    })
//根据商品id加载所有评论
const loadCommodityComments=async (commodityId)=>{
  const res=await request.post("/api/review/listPage",{
    current: currentPage.value,
    pageSize: pageSize.value,
    postId: commodityId, //根据商品id查询
    userId: "", //查看自己的评论
  })
  console.log("根据商品id加载所有评论 res is ",res.data.records)
  comments.value=res.data.records
}
onMounted(()=>{
loadCommodityComments(commodityId)


})

</script>

<style scoped>
.comment-container {
  width: 80%;
  margin-left: 3%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.comment-input {
  margin-bottom: 20px;
}

.comment-input .el-button {
  margin-top: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.time {
  color: #999;
  font-size: 12px;
  margin-top: 2px;
}

.comment-text {
  margin-bottom: 12px;
  line-height: 1.5;
  font-size: 14px;

}

.reply-to {
  color: #fb7299;
  font-weight: bold;
}

.comment-actions {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 13px;
}

.like {
  display: flex;
  align-items: center;
  margin-right: 20px;
  cursor: pointer;
}

.like .el-icon {
  margin-right: 5px;
  font-size: 16px;
}

.reply-btn {
  cursor: pointer;
}

.reply-btn:hover {
  color: #fb7299;
}

.reply-input {
  margin-top: 10px;
  margin-bottom: 10px;
}

.reply-buttons {
  margin-top: 10px;
  text-align: right;
}

.replies {
  margin-top: 15px;
  padding-left: 10px;
}

.reply-item {
  padding: 12px;
  margin-bottom: 10px;
  background-color: #f2f2f2;
  border-radius: 6px;
}

.view-more {
  color: #fb7299;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.view-more .el-icon {
  margin-left: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
